"use client"

import type React from "react"

import { createContext, useContext, useState, useEffect } from "react"
import { useToast } from "@/components/ui/use-toast"

type User = {
  id: string
  name: string
} | null

type UserContextType = {
  user: User
  login: () => void
  logout: () => void
}

const UserContext = createContext<UserContextType | undefined>(undefined)

export function UserProvider({ children }: { children: React.ReactNode }) {
  const [user, setUser] = useState<User>(null)
  const { toast } = useToast()

  // 检查本地存储中是否有用户信息
  useEffect(() => {
    const storedUser = localStorage.getItem("user")
    if (storedUser) {
      setUser(JSON.parse(storedUser))
    }
  }, [])

  // 模拟登录功能
  const login = () => {
    const newUser = {
      id: "user_" + Math.random().toString(36).substr(2, 9),
      name: "学生用户",
    }
    setUser(newUser)
    localStorage.setItem("user", JSON.stringify(newUser))
    toast({
      title: "登录成功",
      description: `欢迎回来，${newUser.name}！`,
    })
  }

  // 登出功能
  const logout = () => {
    setUser(null)
    localStorage.removeItem("user")
    localStorage.removeItem("wrongAnswers")
    localStorage.removeItem("progress")
    toast({
      title: "已退出登录",
      description: "您已成功退出系统",
    })
  }

  return <UserContext.Provider value={{ user, login, logout }}>{children}</UserContext.Provider>
}

export function useUser() {
  const context = useContext(UserContext)
  if (context === undefined) {
    throw new Error("useUser must be used within a UserProvider")
  }
  return context
}

